<template>
    <div class="app-container">
        <el-form
            class="search-form"
            :inline="true"
            size="mini"
            ref="searchForm"
            :model="searchForm"
            label-width="80px"
        >
            <el-form-item label="设置时间">
                <el-date-picker
                    style="width: 220px"
                    :append-to-body="false"
                    :popper-append-to-body="false"
                    v-model="rangeDate"
                    type="daterange"
                    align="right"
                    unlink-panels
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                >
                </el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="doSearch"
                    >搜索</el-button
                >
                <el-button
                    type="default"
                    size="mini"
                    icon="el-icon-refresh"
                    @click="resetData"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>
        <div class="searchs-content">
            <el-button
                v-permission="['om:batchcontrol:add']"
                type="primary"
                size="mini"
                plain
                icon="el-icon-plus"
                @click="addParamDialog"
                >新增</el-button
            >
        </div>
        <Table
            :tableHeader="tableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
        >
            <template slot="action" slot-scope="scope">
                <el-button
                    type="primary"
                    size="mini"
                    @click="paramDetailDialog(scope.row)"
                    >参数</el-button
                >
                <el-button
                    type="success"
                    size="mini"
                    @click="detailDialog(scope.row)"
                    >详情</el-button
                >
            </template>
        </Table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
        />

        <!-- 弹框 -->
        <Dialog
            :visible="detailVisible"
            class="detail-dialog"
            width="50%"
            :isFooter="false"
            title="详情"
            @cancelDialog="cancelDetailDialog"
        >
            <div class="export-btns">
                <el-button
                    type="primary"
                    icon="el-icon-folder-checked"
                    @click="isExport"
                    size="small"
                    :loading="exportBtnLoading"
                    >导出失败设备号</el-button
                >
            </div>
            <div class="table-box">
                <Table
                    :tableHeader="detailTableHeader"
                    :tableData="detailTableData"
                    :tableLoading="detailListLoading"
                >
                    <template
                        slot="action"
                        slot-scope="scope"
                        v-if="scope.row.result !== 1"
                    >
                        <el-button
                            type="primary"
                            plain
                            size="mini"
                            @click="isResend(scope.row)"
                            >重试</el-button
                        >
                    </template>
                </Table>
            </div>
            <pagination
                v-if="detailTotal > 0"
                :total="detailTotal"
                :page.sync="detailForm.pageNum"
                :limit.sync="detailForm.pageSize"
                @pagination="getDetailData"
            />
        </Dialog>
        <!-- 参数 -->
        <Dialog
            :visible="paramDetailVisible"
            width="65%"
            :isFooter="false"
            title="参数"
            @cancelDialog="cancelParamDetailDialog"
        >
            <Params
                :isShow="true"
                :currentParam="currentParam"
                :currentRow="currentRow"
            ></Params>
        </Dialog>
        <!-- 弹框 -->
        <Dialog
            :visible="visible"
            width="80%"
            :isFullscreen="isFullscreen"
            :isFooter="false"
            title="新增批量控制"
            @cancelDialog="cancelDialog"
            class="batchDialog"
        >
            <i class="el-icon-full-screen" @click="onFullscreen"></i>
            <el-form
                class="filters"
                ref="batchSearchForm"
                :model="batchSearchForm"
                label-width="70px"
                size="mini"
            >
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="设备编码" style="width: 100%">
                            <el-input
                                type="textarea"
                                :rows="3"
                                :placeholder="'请输入柜号，多个编码之间请回车换行，禁止输入特殊字符！输入示例：\nCC08DPC0202204250001\nCC08DPC0202205070001\n0000092011500063'"
                                v-model="batchSearchForm.codes"
                                @change.native="keyUp($event)"
                                @input.native="keyInput($event)"
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="19" class="filters">
                        <el-form-item label="厂商" v-if="platformType == 'P'">
                            <el-select
                                v-model="batchSearchForm.organizationId"
                                placeholder="请选择厂商"
                                @change="organizeChange"
                                clearable
                            >
                                <el-option
                                    v-for="item in factuerOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="运营商">
                            <el-select
                                :disabled="!batchSearchForm.organizationId"
                                v-model="batchSearchForm.operatorId"
                                clearable
                                placeholder="请先选择厂商"
                            >
                                <el-option
                                    v-for="item in operatorOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="设备类型">
                            <el-select
                                v-model="batchSearchForm.equipTypeCode"
                                @change="equipTypeChange"
                                placeholder="请选择设备类型"
                            >
                                <el-option
                                    v-for="item in equipTypeOption"
                                    :key="item.code"
                                    :label="item.name"
                                    :value="item.code"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="部件">
                            <el-select
                                v-model="batchSearchForm.partTypes"
                                :disabled="
                                    batchSearchForm.equipTypeCode.length == 0
                                "
                                clearable
                                multiple
                                placeholder="请选择部件"
                            >
                                <el-option
                                    v-for="item in componentList"
                                    :key="item.code"
                                    :label="item.name"
                                    :value="item.code"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="业务状态">
                            <el-select
                                v-model="batchSearchForm.statuses"
                                multiple
                                clearable
                                placeholder="请选择业务状态"
                            >
                                <el-option
                                    v-for="item in businessStatus"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="版本">
                            <el-input
                                v-model="batchSearchForm.version"
                                clearable
                                placeholder="请输入版本"
                            />
                        </el-form-item>
                        <el-form-item label="联网状态">
                            <el-select
                                v-model="batchSearchForm.isOnline"
                                clearable
                                placeholder="请选择联网状态"
                            >
                                <el-option
                                    v-for="item in isOnlineStatus"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="标签">
                            <el-select
                                v-model="batchSearchForm.tagIds"
                                multiple
                                collapse-tags
                                placeholder="请选择标签"
                                clearable
                            >
                                <el-option
                                    v-for="item in tagsOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="地区" class="area-select">
                            <el-cascader
                                :options="areaSelectData"
                                :props="areaSelectDataProps"
                                clearable
                                ref="areaSelectRef"
                                size="large"
                                v-model="batchSearchForm.regionCode"
                                placeholder="请选择省市区"
                            />
                        </el-form-item>
                        <el-form-item label="详细地址">
                            <el-input
                                v-model="batchSearchForm.address"
                                clearable
                                placeholder="请输入详细地址"
                            />
                        </el-form-item>
                        <div class="search-btns detail-search-btns">
                            <el-button
                                type="primary"
                                size="mini"
                                icon="el-icon-search"
                                @click="getDetailList"
                                >搜索</el-button
                            >
                            <el-button
                                type="default"
                                size="mini"
                                icon="el-icon-refresh"
                                @click="resetDialogSearch"
                                >重置</el-button
                            >
                        </div>
                    </el-col>
                </el-row>
            </el-form>
            <el-link
                class="link-text"
                :underline="false"
                type="danger"
                v-if="equipTableData.length > 0"
                >注：设备编码为红色文字的代表当前设备不可用</el-link
            >
            <div
                :style="{
                    height: isFullscreen ? 'auto' : '60vh',
                    'overflow-y': 'auto',
                }"
            >
                <div class="table-box equipTableHeader">
                    <Table
                        :tableHeader="equipTableHeader"
                        :tableData="equipTableData"
                        :tableLoading="handleListLoading"
                    >
                        <template slot="codes" slot-scope="scope">
                            <div class="codes">
                                <span
                                    :class="{
                                        isAllow: !scope.row.isAllowOperate,
                                    }"
                                    >{{ scope.row.code }}</span
                                >
                                <img
                                    v-if="scope.row.isOnline == 1"
                                    src="@/assets/image/online.png"
                                    alt=""
                                />
                                <img
                                    v-else
                                    src="@/assets/image/offline.png"
                                    alt=""
                                />
                            </div>
                        </template>
                        <template slot="tags" slot-scope="scope">
                            <div class="tags-content">
                                <Tags
                                    :currentRow="scope.row"
                                    @updateList="getDetailList"
                                ></Tags>
                                <!-- <i class="el-icon-circle-plus-outline" @click="tagSetShow(scope.row)"></i> -->
                            </div>
                        </template>
                    </Table>
                </div>

                <pagination
                    v-if="equipTotal > 0"
                    :total="equipTotal"
                    :page.sync="batchSearchForm.pageNum"
                    :limit.sync="batchSearchForm.pageSize"
                    @pagination="getDetailList"
                />
                <Params
                    :currentRow="currentRow"
                    :batchSearchForm="equipSearchForm"
                    :equipTableData="equipTableData"
                    @cancelDialog="cancelDialog"
                ></Params>
            </div>
        </Dialog>
    </div>
</template>

<script>
import { equipment, operator } from "@/api/factuer";
import { partType, exportFail } from "@/api/file";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
import { removeNullUndefined } from "@/utils/index.js";
import { handleConfirm } from "@/utils/messageBox";
import { businessStatus, isOnlineStatus } from "@/utils/config";

import Params from "../batchSetting/params.vue";
import { mapGetters } from "vuex";
import Tags from "@/views/equipment/equipentry/components/tags.vue";

export default {
    components: { Pagination, Table, Dialog, Params,Tags },

    data() {
        return {
            listLoading: true,
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                startCreateTime: "",
                endCreateTime: "",
                type: "CONTROL_CONNECTION_PARAM", //区分是批量参数设置还是批量控制
            },
            equipSearchForm: {},
            batchSearchForm: {
                pageNum: 1,
                pageSize: 15,
                organizationId: "",
                equipTypeCode: "",
                operatorId: "",
                partTypes: [],
                statuses: [],
                version: "",
                isOnline: "",
                codes: "",
                regionCode: "",
                address: "",
                tagIds: [],
            },

            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "设置时间",
                    prop: "createTime",
                },
                {
                    label: "操作人",
                    prop: "createBy",
                },
                { slot: "action", label: "操作" },
            ],
            tableData: [],
            detailVisible: false, //弹框标识
            detailTableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "设备编码",
                    prop: "equipCode",
                    width: "120",
                },
                {
                    label: "响应状态",
                    prop: "result",
                    formatter: (item) => {
                        return item.result || item.result == 0
                            ? this.enums.LOG_STATUS.find(
                                  (pp) => pp.code == item.result
                              ).label
                            : "";
                    },
                },
                {
                    label: "上报时间",
                    prop: "reportTime",
                    width: "100",
                },
                { slot: "action", label: "操作" },
            ],
            detailTableData: [],
            detailTotal: 0,
            detailForm: {
                pageNum: 1,
                pageSize: 15,
            },

            dialogTitle: "",
            rangeDate: [],
            currentRow: {},
            exportBtnLoading: false,
            visible: false,
            equipTableData: [],
            equipTableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                { slot: "codes", label: "设备编码" },
                {
                    label: "运营商",
                    prop: "operatorName",
                },
                {
                    label: "设备类型",
                    width: "60",
                    prop: "equipTypeName",
                },
                { slot: "tags", label: "标签" },
            ],
            equipTotal: 0,
            factuerOption: [], //厂商option
            operatorOption: [], //运营商option
            componentList: [],
            equipTypeOption: [], //设备类型option
            areaSelectData: [], // options绑定的数据就是引入的 provinceAndCityData
            areaSelectDataProps: {
                children: "childrens",
                value: "code",
                label: "name",
                emitPath: false,
            },
            businessStatus: businessStatus,
            isOnlineStatus: isOnlineStatus,
            detailListLoading: false,
            handleListLoading: false,
            paramDetailVisible: false,
            currentParam: null,
            platformType: this.$store.state.user.platformType,
            organizationId: this.$store.state.user.organizationId,
            isFullscreen: true, //是否全屏
            tagsOption: [],
        };
    },
    computed: {
        ...mapGetters(["enums", "equipTypeCode"]),
    },

    created() {
        if (this.platformType != "P") {
            //非平台用户
            this.batchSearchForm.organizationId = this.organizationId;
        } else {
        }
        this.fetchData();
    },
    methods: {
        fetchData(val) {
            this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
            this.listLoading = true;
            this.tableData = [];
            this.total = 0;
            let param = { ...this.searchForm };
            if (this.rangeDate && this.rangeDate.length > 0) {
                param.startCreateTime = this.rangeDate[0];
                param.endCreateTime = this.rangeDate[1];
            }
            equipment("/operate/batch/list", "get", {
                ...removeNullUndefined(param),
            })
                .then((response) => {
                    this.tableData = response.data;
                    this.total = +response.total;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },
        getDetailList() {
            this.handleListLoading = true;
            let param = { ...this.batchSearchForm };

            if (param.codes) {
                param.codes = param.codes.split("\n").filter((item) => item);
            }
            if (param.codes.length == 1) {
                param.code = param.codes[0];
                delete param.codes;
            }
            this.equipSearchForm = {
                ...removeNullUndefined(param),
            };
            equipment(
                "/version/list",
                "post",
                {
                    ...removeNullUndefined(param),
                },
                1
            )
                .then((res) => {
                    this.equipTableData = res.data;
                    this.equipTotal = +res.total;
                })
                .finally(() => {
                    this.handleListLoading = false;
                });
        },
        // 弹框取消
        detailDialog(row) {
            this.detailVisible = true;
            this.currentRow = { ...row };
            this.getDetailData();
        },
        getDetailData() {
            this.detailListLoading = true;
            this.detailTableData = [];
            this.detailTotal = 0;
            equipment(
                `/operate/log/list/${this.currentRow.id}`,
                "post",
                {
                    pageNum: this.detailForm.pageNum,
                    pageSize: this.detailForm.pageSize,
                },
                2
            )
                .then((res) => {
                    let datas = res.data ? res.data : [];
                    this.detailTableData = datas;
                    this.detailTotal = res.total ? +res.total : 0;
                })
                .finally(() => {
                    this.detailListLoading = false;
                });
        },
        cancelDetailDialog() {
            this.detailVisible = false;
        },
        cancelParamDetailDialog() {
            this.paramDetailVisible = false;
        },

        // 弹框确认
        confirmDialog() {
            this.submitDialogForm("dialogForm");
        },
        submitDialogForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert("submit!");
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetDialogForm(formName) {
            this.$refs[formName].resetFields();
        },
        resetData() {
            this.searchForm.startCreateTime = "";
            this.searchForm.endCreateTime = "";
            this.rangeDate = [];
        },
        doSearch() {
            this.searchForm.pageNum = 1;
            this.fetchData();
        },
        isExport() {
            handleConfirm("确定要导出失败设备号吗？", "warning", "提示")
                .then((res) => {
                    this.doExportExcel();
                })
                .catch((err) => {});
        },
        doExportExcel() {
            this.exportBtnLoading = true;
            exportFail({
                batchId: this.currentRow.id,
            })
                .then((res) => {
                    if (res.code == 200) {
                        this.$message.success(res.message);
                        this.detailVisible = false;
                    }
                })
                .catch((err) => {
                    if (err && err.data.size == 0) {
                        this.$message.error("暂无失败设备号！");
                    } else if (err && err.data.size > 0) {
                        const content = err.data;
                        const blob = new Blob([content]); //构造一个blob对象来处理数据
                        const fileName = "失败设备号.xlsx";

                        if ("download" in document.createElement("a")) {
                            //支持a标签download的浏览器
                            const link = document.createElement("a");
                            link.download = fileName;
                            link.style.display = "none";
                            link.href = URL.createObjectURL(blob);
                            document.body.appendChild(link);
                            link.click(); //执行下载
                            URL.revokeObjectURL(link.href); //释放url
                            document.body.removeChild(link); //释放标签
                        } else {
                            //其他浏览器
                            navigator.msSaveBlob(blob, fileName);
                        }
                    }
                })
                .finally(() => {
                    this.exportBtnLoading = false;
                });
        },
        // 弹框取消
        cancelDialog(type) {
            this.visible = false;
            this.resetDialogSearch();
            if (type) {
                this.fetchData();
            }
        },
        doResetDialog() {
            this.batchSearchForm = {
                pageNum: 1,
                pageSize: 15,
                organizationId: "",
                equipTypeCode: "",
                operatorId: "",
                partTypes: [],
                statuses: [],
                version: "",
                isOnline: "",
                codes: "",
                regionCode: "",
                address: "",
                tagIds: [],
            };
            this.equipSearchForm = {};
            this.isFullscreen = true;
        },
        resetDialogSearch() {
            this.doResetDialog();
        },
        //限制输入特殊字符
        keyUp(e) {
            let str = e.target.value.replace(
                /[`~!@#$%^&*()_\-+=<>?:"{}|.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
                ""
            );
            e.target.value = str;
            this.batchSearchForm.codes = str;
        },
        // 只能输入汉字、英文、数字
        keyInput(e) {
            let str = e.target.value.replace(/[^\a-\z\A-\Z0-9\n/]/g, "");
            e.target.value = str;
            this.batchSearchForm.codes = str;
        },
        async organizeChange(e) {
            this.operatorOption = [];
            this.batchSearchForm.operatorId = "";
            if (e) {
                let datas = await operator("/all", "get", {
                    organizationId: e,
                });
                this.operatorOption = datas.data;
            }
        },
        async getOperator() {
            this.areaSelectData = await this.$store.dispatch(
                "operator/generatorRegion"
            );
            this.equipTypeOption = await this.$store.dispatch(
                "operator/generatorEquipType"
            );
            this.tagsOption = await this.$store.dispatch(
                "operator/generatorTags"
            );
            if (this.equipTypeOption.length > 0) {
                this.batchSearchForm.equipTypeCode =
                    this.equipTypeOption[0].code;
                this.equipTypeChange(this.batchSearchForm.equipTypeCode);
            }
            this.getDetailList();
        },
        async equipTypeChange(e) {
            this.componentList = [];
            this.batchSearchForm.partTypes = [];
            let data = await partType("/list", "get", { equipTypeCode: e });
            this.componentList = data.data;
        },
        async addParamDialog() {
            this.visible = true;
            this.currentRow = {
                type: this.searchForm.type,
            };
            if (this.platformType == "P" && this.factuerOption.length == 0) {
                this.factuerOption = await this.$store.dispatch(
                    "operator/generatorFactuer"
                );
            }
            if (
                this.areaSelectData.length == 0 ||
                this.equipTypeOption.length == 0
            ) {
                this.getOperator();
            } else {
                this.batchSearchForm.equipTypeCode =
                    this.equipTypeOption[0].code;
                this.equipTypeChange(this.batchSearchForm.equipTypeCode);
                this.getDetailList();
            }
            if (this.platformType != "P" && this.operatorOption.length == 0) {
                this.organizeChange(this.organizationId);
            }
        },
        paramDetailDialog(row) {
            this.currentParam = JSON.parse(row.param);
            this.paramDetailVisible = true;
            this.currentRow = { ...row };
        },
        isResend(row) {
            handleConfirm("确定要重试吗？", "warning", "提示")
                .then((res) => {
                    this.detailListLoading = true;
                    equipment(`/operate/resent/${row.id}`, "post")
                        .then((res) => {
                            if (res.code == 200) {
                                this.$message.success(res.message);
                                this.detailTableData[
                                    this.detailTableData
                                        .map((item) => item)
                                        .indexOf(row.id)
                                ].result = 1;
                            }
                        })
                        .finally(() => (this.detailListLoading = false));
                })
                .catch((err) => {});
        },
        onFullscreen() {
            this.isFullscreen = !this.isFullscreen;
        },
    },
};
</script>
<style scoped lang="scss">
@import "@/styles/common.scss";

.search-form {
    .el-form-item {
        margin-bottom: 8px;
    }
}

.export-btns {
    text-align: right;
    margin-bottom: 10px;
}

.filters {
    margin-bottom: 0;
    .el-form-item {
        width: 17%;
    }
    .el-form-item__content {
        width: auto;
    }
}

.codes {
    @include flexLayout(center, center);

    img {
        width: 20px;
        margin-left: 10px;
    }

    .isAllow {
        color: red;
    }
}

.el-icon-full-screen {
    position: absolute;
    right: 45px;
    color: rgb(144, 147, 153);
    cursor: pointer;
    font-size: 22px;
    display: inline-block;
    margin-top: -36px;
    font-weight: bold;
}

.link-text {
    margin-bottom: 10px;
    font-weight: bold;
}

.detail-dialog {
    ::v-deep .el-table__empty-block {
        min-height: 160px;
    }
    ::v-deep .el-dialog__header {
        padding-bottom: 0;
    }
    ::v-deep .el-dialog__body {
        padding-top: 0;
    }
    ::v-deep .pagination-container {
        padding: 10px 16px;
    }
}
.batchDialog {
    ::v-deep .el-dialog__body {
        padding: 0 20px 10px;
    }
    ::v-deep .pagination-container {
        padding: 10px;
    }
}
.equipTableHeader {
    height: 320px !important;
}
::v-deep .el-select__tags{
    .el-tag:first-child{
        max-width: 72%;
    }
}
</style>
